package site.jlopen.kuscia.rpc.impl;

import java.io.FileNotFoundException;

import org.secretflow.v1alpha1.factory.KusciaAPIChannelFactory;
import org.secretflow.v1alpha1.kusciaapi.Health.HealthRequest;
import org.secretflow.v1alpha1.kusciaapi.Health.HealthResponse;
import org.secretflow.v1alpha1.kusciaapi.HealthServiceGrpc;
import org.secretflow.v1alpha1.kusciaapi.HealthServiceGrpc.HealthServiceBlockingStub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import site.jlopen.kuscia.rpc.KusciaHealthRpc;
import site.jlopen.kuscia.exception.SdkBaseException;
import site.jlopen.kuscia.properties.KusciaAPIProperties;

import io.grpc.ManagedChannel;

public class KusciaHealthRpcImpl implements KusciaHealthRpc {
	private static Logger logger = LoggerFactory.getLogger(KusciaHealthRpcImpl.class);

	private HealthServiceBlockingStub blockingStub;
	private ManagedChannel channel;

	public KusciaHealthRpcImpl(KusciaAPIProperties properties) {
		try {
			KusciaAPIChannelFactory channelFactory = new KusciaAPIChannelFactory(properties.getAddress(),
					properties.getTokenFile(), properties.getTls(), properties.getProtocol());
			this.channel = channelFactory.newClientChannel();
			this.blockingStub = HealthServiceGrpc.newBlockingStub(channel);
		} catch (Exception e) {
			if(e instanceof FileNotFoundException) {
				throw SdkBaseException.of("证书文件不存在", e);
			}
			throw SdkBaseException.of("Channel通讯异常", e);
		}
	}

	@Override
	public HealthResponse healthZ(HealthRequest request) {
		try {
			HealthResponse response = blockingStub.healthZ(request);
			checkResponse(response.getStatus());
			return response;
		} catch (Exception e) {
			logger.error("批量查询节点状态：{}", e);
		} finally {
			channel.shutdownNow();
		}
		return null;
	}

}
